package com.as.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by 汪贵春 on 2017/2/27.
 */
public class QRCodeUtils {

    //创建二维码图片
    public static BufferedImage creatBufferedImage(String content) {
        BitMatrix bitMatrix = getBitMatrix(content);
        BufferedImage image = new BufferedImage(bitMatrix.getWidth(), bitMatrix.getHeight(), BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < bitMatrix.getWidth(); x++) {
            for (int y = 0; y < bitMatrix.getHeight(); y++) {
                image.setRGB(x, y, bitMatrix.get(x, y) ?
                        Color.BLACK.getRGB() : Color.WHITE.getRGB());
            }
        }
        return image;
    }


    //创建二维码矩阵
    public static BitMatrix getBitMatrix(String content) {
        Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        int width = 500;//图片的宽度
        int height = 500;//图片的高度
        QRCodeWriter writer = new QRCodeWriter();
        BitMatrix m = null;
        try {
            m = writer.encode(content, BarcodeFormat.QR_CODE, height, width, hints);
        } catch (WriterException e) {
            e.printStackTrace();
        }
        return m;
    }

}
